package tom_io_nio.nio.buffer;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class DirectBuffer {

    public static void main(String[] args) throws Exception{

        //读取本地文件
        FileInputStream fis = new FileInputStream("/Users/mac/Desktop/test.txt");

        //获取管道
        FileChannel channel = fis.getChannel();

        //把内容写到另一个文件中
        String outfile = String.format("/Users/mac/Desktop/test1.txt");
        FileOutputStream outputStream = new FileOutputStream(outfile);
        FileChannel outChannel = outputStream.getChannel();


        //创建缓冲区，使用allocateDirect  而不是allocate
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

        while (true){
            buffer.clear();

            int r = channel.read(buffer);
            if(r == -1){
                break;
            }
            buffer.flip();
            outChannel.write(buffer);
        }

        fis.close();
        outputStream.close();
        channel.close();
        outChannel.close();
    }
}
